<?php

namespace addons\qingdongams\controller;

use addons\qingdongams\model\AttendanceRule;
use addons\qingdongams\model\AttendanceStatisc;
use addons\qingdongams\model\AttendanceTime;
use addons\qingdongams\library\JuheExpress;
use addons\qingdongams\model\Attendance;
use addons\qingdongams\model\Leads;
use addons\qingdongams\library\ReceiveMail;
use addons\qingdongams\model\AdminConfig;
use addons\qingdongams\model\Contract;
use addons\qingdongams\model\Customer;
use addons\qingdongams\model\CustomerType;
use addons\qingdongams\model\Message;
use addons\qingdongams\model\Receivables;
use addons\qingdongams\model\Staff;
use addons\qingdongams\model\StaffSignIn;
use addons\qingdongams\model\StaffTeam;
use addons\qingdongams\model\StaffTeamList;
use addons\qingdongams\model\Quote;
use addons\qingdongams\model\Workorder;
use addons\qingdongams\model\WorkorderLogistics;
use addons\qingdongams\model\WorkReport;
use addons\qingdongams\model\Event;
use addons\qingdongams\model\Record;
use fast\Http;
use think\Db;
use think\Exception;
use think\Log;
use addons\qingdongams\library\Wechat;
use addons\qingdongams\library\WechatEnterprise;
use addons\qingdongams\model\WechatOpenid;

@header('Content-type: text/html;charset=UTF-8');
error_reporting(0);
ignore_user_abort(); // run script in background
set_time_limit(0); // run script forever
date_default_timezone_set('Asia/Shanghai');

class Autotask
{
    public $mailServer = "pophz.qiye.163.com";
    public $serverType = "pop3";
    public $port = "110";
    protected $now = 0;
    protected $savePath;
    protected $webPath;
    protected $formater = ['gif', 'jpeg', 'png', 'jpg', 'bmp'];

    public function __construct()
    {
        try{
            \think\Db::execute("SET @@sql_mode='';");
        }catch (Exception $e){

        }
        $this->prikey = AdminConfig::where(array('type'=>'wechat','field'=>'email_key'))->value('value');
        $this->savePath = ROOT_PATH;
        $this->webPath = "../emails/";
    }

    //订单到期提醒
    public function contract()
    {
        $endDate = date('Y-m-d', strtotime('+3 day'));
        $contracts = Contract::where(['check_status' => 2, 'contract_status' => 0, 'end_time' => ['lt', $endDate]])->select();
        try {
            //订单即将到期通知
            foreach ($contracts as $v) {
                Message::addMessage(Message::CONTRACT_EXPIRE_TYPE, $v['id'], $v['owner_staff_id'], 0,'订单即将到期，请尽快跟进回款');
            }
        } catch (Exception $e) {
            return $e->getMessage();
        }
        $this->plan();
        $this->visitWorkorderMessage();
        return 'success';
    }

    //回款计划通知
    public function plan()
    {
        $endDate = date('Y-m-d', strtotime('+1 day'));
        //进行中 -- 待回款
        $plans = \addons\qingdongams\model\ReceivablesPlan::where(['status' => 0, 'remind_date' => ['lt', $endDate]])->select();

        try {
            //订单即将到期通知
            foreach ($plans as $v) {
                Message::addMessage(Message::PLAN_EXPIRE_TYPE, $v['contract_id'], $v['owner_staff_id'],0, '已到计划回款约定时间，请尽快跟进回款');
            }
        } catch (Exception $e) {
            return $e->getMessage();
        }

        return 'success';
    }

    //日程提醒
    public function event()
    {
        $endDate = date('Y-m-d H:i:s');
        $events = \addons\qingdongams\model\Event::where(['status' => 0, 'remind_time' => ['lt', $endDate]])->select();

        $endIds = \addons\qingdongams\model\Event::where([
            'status' => ['in', [0, 1]],
            'end_time' => ['lt', $endDate]
        ])->column('id');

        try {
            //日程自动结束
            Event::where(['id' => ['in', $endIds]])->update(['status' => 2]);

            //日程时间提醒
            foreach ($events as $v) {
                if (Message::where([
                    'relation_type' => Message::EVENT_TYPE,
                    'relation_id' => $v['id'],
                    'to_staff_id' => $v['staff_id']
                ])->count()) {
                    //已经提醒过了
                    continue;
                }
                Message::addMessage(Message::EVENT_TYPE, $v['id'], $v['staff_id'],0, $v['title'] . '日程即将开始');
            }
        } catch (Exception $e) {
            return $e->getMessage();
        }
        return 'success';
    }

    //公海
    public function seas()
    {
        if (AdminConfig::getConfigValue('auto', AdminConfig::TYPE_SEAS)) {//自动回收客户
            if (AdminConfig::getConfigValue('genjing', AdminConfig::TYPE_SEAS) == 1) {//未跟进客户回收
                $day = AdminConfig::getConfigValue('genjing_day', AdminConfig::TYPE_SEAS);
                $genjing_c_name = AdminConfig::getConfigValue('genjing_c_name', AdminConfig::TYPE_SEAS);
                $where = [
                    'receivetime' => ['<', strtotime('-' . $day . ' day')],
                    'last_time' => ['<', date('Y-m-d H:i:s', strtotime('-' . $day . ' day'))]];
                if ($genjing_c_name) {
                    $where['name'] = ['like', "%{$genjing_c_name}%"];
                }
                if (AdminConfig::getConfigValue('genjing_success', AdminConfig::TYPE_SEAS) == 1) {
                    $where['contract_status'] = 0;
                }
                $customers = Customer::where($where)->field('id,name,owner_staff_id')->select();
                try {
                    foreach ($customers as $c) {
                        Customer::moveSeas($c['id']);
                        Message::addMessage(Message::SEAS_TYPE, $c['id'], $c['owner_staff_id'], 0, "您的客户`{$c['name']}`长时间未跟进，已被系统自动回收到公海池内。");
                    }
                } catch (Exception $e) {
                    Log::error($e->getMessage());
                }
            }
            if (AdminConfig::getConfigValue('chengjiao', AdminConfig::TYPE_SEAS) == 1) {//未成交客户回收
                $day = AdminConfig::getConfigValue('chengjiao_day', AdminConfig::TYPE_SEAS);
                $chengjiao_c_name = AdminConfig::getConfigValue('chengjiao_c_name', AdminConfig::TYPE_SEAS);

                $where = [
                    'receivetime' => ['<', strtotime('-' . $day . ' day')],
                    'contract_status' => 0
                ];
                if ($chengjiao_c_name) {
                    $where['name'] = ['like', "%{$chengjiao_c_name}%"];
                }
                $customers = Customer::where($where)->field('id,name,owner_staff_id')->select();
                try {
                    foreach ($customers as $c) {
                        Customer::moveSeas($c['id']);
                        Message::addMessage(Message::SEAS_TYPE, $c['id'], $c['owner_staff_id'], 0, "您的客户`{$c['name']}`长时间未成交，已被系统自动回收到公海池内。");
                    }
                } catch (Exception $e) {
                    Log::error($e->getMessage());
                }
            }


            if (1 == 1) {//24小时不联系回收
                $day = 1;

                $where = [
                    'receivetime' => ['>', strtotime('-' . $day . ' day')],
                    'last_time' => ['<', date('Y-m-d H:i:s', strtotime('-' . $day . ' day'))]
                ];
                $customers = Customer::where($where)->field('id,name,owner_staff_id')->select();
                try {
                    foreach ($customers as $c) {
                        Customer::moveSeas($c['id']);
                        Message::addMessage(Message::SEAS_TYPE, $c['id'], $c['owner_staff_id'], 0, "您新领取的客户`{$c['name']}`24小时未联系，已被系统自动回收到公海池内。");
                    }
                } catch (Exception $e) {
                    Log::error($e->getMessage());
                }
            }
        }
        return 'success';
    }

    /**
     * 线索池分配
     */
    public function leadpool(){
        if(AdminConfig::getConfigValue('leadauto', AdminConfig::TYPE_LEAD)){
            $leadauto = AdminConfig::getConfigValue('leadauto', AdminConfig::TYPE_LEAD);
            $lead_day = AdminConfig::getConfigValue('lead_day', AdminConfig::TYPE_LEAD);
            $attendance = AdminConfig::getConfigValue('leadcard', AdminConfig::TYPE_LEAD);
            $department = AdminConfig::getConfigValue('department', AdminConfig::TYPE_LEAD);

            //开启分配
            if($leadauto == 1 && $lead_day>0 && $department){
                $leadpool = Leads::where('owner_staff_id is null or owner_staff_id = 0')->order('id desc')->limit(100)->column('id');
                if($leadpool){
                    $department = explode(',',$department);
                    $staffinfo = array();
                    foreach($department as $k=>$v){
                        $staffids = Staff::where('', 'exp', Db::raw('FIND_IN_SET(' . $v . ',group_ids)'))->where(['status'=>1])->column('id');
                        $staffinfo[] = $staffids;
                    }
                    if(!$staffinfo){
                        return '无数据';
                    }
                    $staffinfos =[];
                    foreach($staffinfo as $k=>$v){
                        foreach($v as $ks=>$vs){
                            $staffinfos[] = $vs;
                        }
                    }
                    $staff = array_unique($staffinfos);
                    foreach($leadpool as $ks=>$vs){
                        $stafflead =[];
                        foreach($staff as $k=>$v){
                            if($attendance == 1){ //打卡
                                $whereC['staff']= $v;
                                $whereC['createtime'] = array(array('egt',strtotime(date('Y-m-d 00:00:00'))),array('elt',strtotime(date('Y-m-d 23:59:59'))));
                                $leadcard = Attendance::where($whereC)->find();
                                if(!$leadcard){//未打卡不分配
                                    continue;
                                }
                            }
                            $wherelead['owner_staff_id'] = $v;
                            $wherelead['receive_time'] = array(array('egt',strtotime('-'.$lead_day.' days',time())),array('elt',time()));
                            $lead = Leads::where($wherelead)->count();
                            $stafflead[] = array(
                                'id'=>$v,
                                'num'=>$lead
                            );
                        }
                        if($stafflead){
                            $num_count = array_column($stafflead,'num');//返回数组中指定的一列
                            array_multisort($num_count,SORT_ASC,$stafflead);
                            Leads::where(array('id'=>$vs))->update(array('owner_staff_id'=>$stafflead[0]['id'],'receive_time'=>time()));
                        }
                    }

                }

            }
        }
        return 'success';
    }


    //工作报告 日志
    public function dayWorkorder()
    {
        $type=input('type');
        if ($type == '日') {
            $time = date('Y-m-d', strtotime('-1 day'));
            $startDate = strtotime($time);
            //月底
            $endDate = strtotime($time . '+1 day') - 1;
        } elseif ($type == '周') {
            $time = date('Y-m-d', strtotime('-1 monday', time()));
            $startDate = strtotime($time);
            //月底
            $endDate = strtotime($time . '+1 week') - 1;
        } elseif ($type == '月') {
            $time = date('Y-m-d', strtotime('-1 month', strtotime(date('Y-m', time()) . '-01 00:00:00')));;
            $startDate = strtotime($time);
            //月底
            $endDate = strtotime($time . '+1 month') - 1;
        } elseif ($type == '季') {
            $season = ceil((date('n')) / 3) - 1;
            $time = date('Y-m-d', mktime(0, 0, 0, $season * 3 - 3 + 1, 1, date('Y')));
            $startDate = strtotime($time);
            //月底
            $endDate = strtotime($time . '+3 month') - 1;
        } elseif ($type == '年') {

            $time = date('Y-1-1', strtotime('-1 year'));
            $startDate = strtotime($time);
            //月底
            $endDate = strtotime($time . '+1 year') - 1;
        } else {
            return '链接必须带参数';
        }

        $workreportModel = new WorkReport();
        $find = $workreportModel->where([
            'report_date' => $time,
            'type' => $type
        ])->find();
        if ($find) {
            return '已生成日报';
        }
        //跟进记录
        $followUp = Record::where([
            'relation_type' => 1,
            'createtime' => ['between', [$startDate, $endDate]],
        ])->group('staff_id')->field('staff_id,count(*) as count,group_concat(id) as id_list')->select();

        $followUp = $this->setStaffList($followUp);

        //获客 客户
        $customer = Customer::where([
            'createtime' => ['between', [$startDate, $endDate]],
        ])->group('create_staff_id')->field('create_staff_id,count(*) as count,group_concat(id) as id_list')->select();
        $customer = $this->setStaffList($customer);

        //订单
        $contract = Contract::where([
            'createtime' => ['between', [$startDate, $endDate]],
            'check_status' => 2
        ])->group('create_staff_id')->field('create_staff_id,count(*) as count,group_concat(id) as id_list,sum(money) as money')->select();
        $contract = $this->setStaffList($contract);
        //报价
        $quote = Quote::where([
            'createtime' => ['between', [$startDate, $endDate]],
            'check_status' => 2
        ])->group('create_staff_id')->field('create_staff_id,count(*) as count,group_concat(id) as id_list')->select();
        $quote = $this->setStaffList($quote);
        //
        $order = \addons\qingdongams\model\Order::where([
            
            'createtime' => ['between', [$startDate, $endDate]],
        ])->group('create_staff_id')->field('create_staff_id,count(*) as count,group_concat(id) as id_list')->select();
        $order = $this->setStaffList($order);

        //回款次数
        $receivables = Receivables::where([
            'createtime' => ['between', [$startDate, $endDate]],
            'check_status' => 2
        ])->group('create_staff_id')->field('create_staff_id,count(*) as count,group_concat(id) as id_list,sum(money) as money')->select();
        $receivables = $this->setStaffList($receivables);

        //拜访次数
        $visit = Event::where([
            'event_type' => ['like',"客户服务%"],
            'actual_end_time' => ['between', [$startDate, $endDate]],
            'status' => 2
        ])->group('staff_id')->field('staff_id,count(*) as count,group_concat(id) as id_list,sum(use_time) as time')->select();
        $visit = $this->setStaffList($visit);

        //新建工单
        $workorder = Workorder::where([
            'createtime' => ['between', [$startDate, $endDate]]
        ])->group('create_staff_id')->field('create_staff_id,count(*) as count,group_concat(id) as id_list')->select();
        $workorder = $this->setStaffList($workorder);
        //完成工单数量
        $completeWorkorder = Workorder::where([
            'status' => 3,
            'end_time' => ['between', [$startDate, $endDate]]
        ])->group('owner_staff_id')->field('owner_staff_id,count(*) as count,group_concat(id) as id_list,sum(money) as money')->select();
        $completeWorkorder = $this->setStaffList($completeWorkorder);
        //好评工单
        $goodWorkorder = Workorder::where([
            'comment_score' => 5,
            'status' => 3,
            'end_time' => ['between', [$startDate, $endDate]]
        ])->group('owner_staff_id')->field('owner_staff_id,count(*) as count,group_concat(id) as id_list')->select();
        $goodWorkorder = $this->setStaffList($goodWorkorder);

        //未完成日程
        $notEvent = Event::where([
            'createtime' => ['between', [$startDate, $endDate]],
            'status' => ['in', [0, 1]]
        ])->group('staff_id')->field('staff_id,count(*) as count,group_concat(id) as id_list')->select();
        $notEvent = $this->setStaffList($notEvent);

        //完成日程及任务
        $completeEvent = Event::where([
            
            'actual_end_time' => ['between', [$startDate, $endDate]],
            'status' => 2
        ])->group('staff_id')->field('staff_id,count(*) as count,group_concat(id) as id_list,sum(use_time) as time')->select();
        $completeEvent = $this->setStaffList($completeEvent);

        $staff = Staff::where(['status'=>1])->field('id,name')->select();
        $insertAll = [];

        foreach ($staff as $v) {

            $customerinfo = $customer[$v['id']] ?? '';
            $visitinfo = $visit[$v['id']] ?? '';
            $quoteinfo =   $quote[$v['id']] ?? '';
            $contractinfo = $quote[$v['id']] ?? '';
            $orderinfo = $order[$v['id']] ?? '';
            $receivablesinfo = $receivables[$v['id']] ?? '';
            $workorderinfo = $workorder[$v['id']] ?? '';
            $complete_workorderinfo = $completeWorkorder[$v['id']] ?? '';
            $good_workorderinfo = $goodWorkorder[$v['id']] ?? '';
            $not_eventinfo=$notEvent[$v['id']] ?? '';
            $complete_eventinfo = $completeEvent[$v['id']] ?? '';
            $follow_upinfo = $followUp[$v['id']] ?? '';
            if(!$customerinfo && !$visitinfo && !$quoteinfo && !$contractinfo && !$orderinfo && !$receivablesinfo &&
                !$workorderinfo && !$complete_workorderinfo && !$good_workorderinfo && !$not_eventinfo && !$complete_eventinfo && !$follow_upinfo){
                continue;
            }
            $insertAll[] = [
                'staff_id' => $v['id'],
                'report_date' => $time,
                'type' => $type,
                'customer' => $customer[$v['id']] ?? '',//获客
                'visit' => $visit[$v['id']] ?? '',//拜访
                'quote' => $quote[$v['id']] ?? '',//拜访
                'contract' => $contract[$v['id']] ?? '',//订单
                'order' => $order[$v['id']] ?? '',//订单
                'receivables' => $receivables[$v['id']] ?? '',//回款
                'workorder' => $workorder[$v['id']] ?? '',//工单
                'complete_workorder' => $completeWorkorder[$v['id']] ?? '',//完成工单数量
                'good_workorder' => $goodWorkorder[$v['id']] ?? '',//好评工单数量
                'not_event' => $notEvent[$v['id']] ?? '',//未完成日程
                'complete_event' => $completeEvent[$v['id']] ?? '',//已完成日程
                'follow_up' => $followUp[$v['id']] ?? '',//跟进
            ];
        }
        if(!$insertAll){
            return '数据为空';
        }
        if ($workreportModel->allowField(true)->isUpdate(false)->saveAll($insertAll) == false) {
            return '保存失败';
        }
        $list = $workreportModel->where([ 'report_date' => $time, 'type' => $type])->select();
        foreach ($list as $v) {
            if ($type == '日') {
                $content = $time . '个人日报已经生成';
            } elseif ($type == '周') {
                $content = $time . '上周周报已经生成';
            } elseif ($type == '月') {
                $content = $time . '上月月报已经生成';
            } elseif ($type == '季') {
                $content = $time . '上季季报已经生成';
            } elseif ($type == '年') {
                $content = $time . '上年年报已经生成';
            }
            Message::addMessage(Message::WORKREPORT_TYPE, $v['id'], $v['staff_id'], 0, $content, 7);
        }
        return '成功';
    }

    //查询快递
    public function getCompanys()
    {
        $logistics = WorkorderLogistics::where(['status' => 0])->select();
        $juheExpress = new JuheExpress();
        $workorderLogistics = new WorkorderLogistics();
        foreach ($logistics as $v) {
            $result = $juheExpress->getResult('sf', $v['number'],'7836');
            if(empty($result)){
                continue;
            }
            $list = $result['list'];
            $data = [];
            foreach ($list as $ves) {
                $data[] = ['text' => $ves['datetime'], 'desc' => $ves['remark']];
            }
            $lastList = $data[count($data) - 1];
            $workorderLogistics->where(['id' => $v['id']])->update([
                'content' => json_encode($data),
                'current_status' => json_encode($lastList),
                'status' => $result['status'],
            ]);
        }

        return 'success';
    }

    //生成列表
    private function setStaffList($list)
    {
        $list = collection($list)->toArray();
        $data = [];
        foreach ($list as $v) {
            $staff_id = $v['create_staff_id'] ?? $v['staff_id'] ?? $v['owner_staff_id'];
            $data[$staff_id] = json_encode($v);
        }
        return $data;
    }

    // 销售消息提醒
    public function staffCusTypeRemain(){
        $typeList = CustomerType::where(['cus_status'=>1])->column('days_cus','name');
        if(!$typeList){
            echo '未开启提醒';exit;
        }
        foreach($typeList as $k=>$v){
            $date = date("Y-m-d",strtotime("-$v days"));
            $this->typeStaffMessage($k,$date,$v);
        }
        $this->leaderCusTypeRemain();
        echo "over";
    }
    // 领导消息提醒
    public function leaderCusTypeRemain(){
        $typeList = CustomerType::where(['pid_status'=>1])->column('(days_pid+days_cus)','name');
        if(!$typeList){
            echo '未开启提醒';exit;
        }
        $staffTeam = StaffTeamList::where([])->column('team_id','staff_id');// 员工团队表
        $teamInfo = StaffTeam::where([])->column('staff_id','id');// 团队详情
        foreach($typeList as $k=>$v){
            $date = date("Y-m-d",strtotime("-$v days"));
            $this->typeLeaderMessage($k,$date,$v,$staffTeam,$teamInfo);
        }
        echo "over";
    }
    // 消息提醒
    public function typeStaffMessage($k,$date,$days){
        $customerModel = new Customer();
        $list = collection($customerModel->where(['contract_status'=>0,'type'=>$k,'claimdate'=>$date])->select())->toArray();
        if(!$list) return true;
        foreach ($list as $key=>$v){
            $content = $k.'类客户['.$v['name'].']已领用'.$days.'天，但仍未成交';
            Message::addMessage(Message::CUSTOMER_NODEAL, $v['id'], $v['owner_staff_id'], 0, $content, 10);
        }
    }
    // 消息提醒给领导
    public function typeLeaderMessage($k, $date, $days, $staffTeam, $teamInfo){
        $customerModel = new Customer();
        $list = collection($customerModel->with('ownerStaff')->where(['contract_status'=>0,'type'=>$k,'claimdate'=>$date])->select())->toArray();
        if(!$list) return true;
        foreach ($list as $key=>$v){
            $hasMessage = Message::where(['relation_type'=>Message::CUSTOMER_TYPE_MESSAGE,'relation_id'=>$v['id'],'from_staff_id'=>$v['owner_staff_id']])->find();
            if($hasMessage){
                continue;
            }
            $content = '['.$v['owner_staff']['name'].']下'.$k.'类客户['.$v['name'].']已领用'.$days.'天，但仍未成交';
            $toMessageId = $teamInfo[$staffTeam[$v['owner_staff_id']]];
            Message::addMessage(Message::CUSTOMER_NODEAL, $v['id'], $toMessageId, 0, $content, 10);
        }


    }


    //回访工单提醒
    public function visitWorkorderMessage()
    {
        $workorders = Workorder::where(['status' => 3,
            'is_visit' => 0,
            'workorder_type' => ['in', Workorder::getVisitType()],
            'end_time' => ['lt', time()-86400*3]])->select();

        foreach ($workorders as $v) {
            $content = "工单[{$v['title']}]完成3天后未回访客户，请及时跟进!";
            Message::addMessage(Message::WORKORDER_TYPE, $v['id'], $v['create_staff_id'], 0, $content, 10);
            Message::addMessage(Message::WORKORDER_TYPE, $v['id'], $v['owner_staff_id'], 0, $content, 10);
        }

        return 'success';
    }

    //解析客户地址
    public function customerAddress(){
        $customer=Customer::where('lng','null')->where(['address'=>['neq',''],'address_detail'=>['neq','']])->field('id,address,address_detail')->select();
        foreach ($customer as $v){
            $address=$v['address'].$v['address_detail'];
            if(empty($address)){
                continue;
            }
            $url="https://apis.map.qq.com/ws/geocoder/v1/?address={$address}&key=";
            $result=file_get_contents($url);
            $result=json_decode($result,true);
            if(empty($result)){
                continue;
            }
            if($result['status'] == 0){
                $lng=$result['result']['location']['lng'];
                $lat=$result['result']['location']['lat'];
            }else{
                $lng=1;
                $lat=1;
            }
            Customer::where(['id'=>$v['id']])->update(['lng'=>$lng,'lat'=>$lat]);
        }
        return 'success';
    }


    // 邮箱定时 pop 服务器直接请求
    public function autogetemails()
    {
        set_time_limit(0);
        $where['email'] = [['not null',''],['neq',''],'and'];
        $where['email_code'] = [['not null',''],['neq',''],'and'];
        $where['status'] = 1;
        $list = \addons\qingdongams\model\Staff::where($where)->field('id,email,email_code,name')->select();

        if (count($list) < 1) {
            return '失败';
        }
        $list = collection($list)->toArray();
        $emailModel = new \addons\qingdongams\model\ReceiveEmail();
        $genjinModel = new StaffSignIn();
        foreach ($list as $K => $v) {
            $addList = $genjinList = [];
            $obj = new  ReceiveMail($v['email'], $v['email_code'], $v['email'], $this->mailServer, $this->serverType, $this->port, false);
            //Connect to the Mail Box
            $res = $obj->connect();
            if (!$res) {
                echo "Error: Connecting to mail server";
                continue;
            }
            // Get Total Number of Unread Email in mail box
            $tot = $obj->getTotalMails(); //Total Mails in Inbox Return integer value
            echo $tot . '封邮件';
            if ($tot < 1) { //如果信件数为0,显示信息
                echo "No Message for " . $v['email'];
                continue;
            } else {
                Db::startTrans();
                try {
                    $customerId = '';// 客户id
                    for ($i = $tot; $i > 0; $i--) {
                        $head = $obj->getHeaders($i);  // Get Header Info Return Array Of Headers **Array Keys are (subject,to,toOth,toNameOth,from,fromName)
                        Log::write($v['name'] . $i . '头部内容'.json_encode($head));
                        if(!$head) continue;
                        if ($emailModel->where(['uuid' => $head['udate']])->find()) {
                            Log::write($v['name'] . '邮箱：' . $v['email'] . $head['udate'] . '已存储');
                            continue;
                        }
                        $detail = [
                            'uuid' => $head['udate'],
                            'staff_id' => $v['id'],
                            'staff_name' => $v['name'],
                            'from_account' => $head['fromBy'],
                            'from_name' => $head['fromName'],
                            'receivetime' => $head['mailDate'],
                            'theme' => $head['subject'],
                        ];
                        $customerId = \addons\qingdongams\model\Contacts::where(['email' => $head['fromBy']])->value('customer_id');
                        //处理邮件附件
                        $files = $obj->GetAttach($i, $this->savePath); // 获取邮件附件，返回的邮件附件信息数组
                        Log::write($v['name'] . $i . '附件：----' . json_encode($files));
                        $imageList = $attachIds = $imgIds = array();
                        if ($files) {
                            foreach ($files as $k => $file) {
                                //type=1为附件,0为邮件内容图片
                                if ($file['type'] == 0) {
                                    $imageList[$file['title']] = $file['pathname'];
                                }
                                //附件列表
                                $file_path = str_replace('public', '', $file['pathname']);
                                $attach = [
                                    'types' => 'file',
                                    'name' => $file['title'],
                                    'save_name' => $file['pathname'],
                                    'size' => is_numeric($file['size']) ? $file['size'] : 0,
                                    'file_path' => $file_path,
                                    'file_path_thumb' => '',
                                    'create_staff_id' => $v['id'],
                                    'createtime' => time(),
                                    'updatetime' => time(),
                                ];
                                if (in_array($file['extension'], $this->formater)) {
                                    $attach['types'] = 'image';
                                }
                                if (!$file = \addons\qingdongams\model\File::create($attach)) {
//                                    Log::write(\addons\qingdongams\model\File::getError().'----'.\addons\qingdongams\model\File::getLastSql());
                                    throw new Exception(\addons\qingdongams\model\File::getError() . '----' . \addons\qingdongams\model\File::getLastSql());
                                }
                                if($attach['types'] == 'image'){
                                    $imgIds[] = $file->id;
                                }else{
                                    $attachIds[] = $file->id;
                                }

                            }
                        }
                        $detail['imgs'] = implode(',', $imgIds);
                        $detail['attach'] = implode(',', $attachIds);
                        $genjin = [
                            'staff_id' => $v['id'],
                            'location' => '',
                            'lng' => '',
                            'lat' => '',
                            'files' => $detail['attach'],
                            'customer_id' => $customerId,//客户id
                            'relation_type' => StaffSignIn::CUSTOMER_TYPE,//日程类型 客户
                            'relation_id' => $customerId,//签到关联发送邮件id
                            'relation_process' => '邮箱回复',//进度
                            'content' => $head['subject'],
                            'distance' => '',
                        ];
                        $body = $obj->getBody($i, $this->webPath, $imageList);
                        $detail['content'] = $body;
                        $addList[] = $detail;
                        $genjinList[] = $genjin;
                        Log::write($v['name'] . $i . '内容：----' . $body);
                    }
                    $res = $emailModel->saveAll($addList);
                    $res1 = $genjinModel->saveAll($genjinList);
                    if ($res === false) {
                        Log::write($v['name'] . $i . '存储失败：----' . $emailModel->getError().'===='. $emailModel->getLastSql());
                        throw new Exception($emailModel->getError() . '----' . $emailModel->getLastSql());
                    }
                    Db::commit();
                    $content = '您有新邮件，请注意查收！';
                    Message::addMessage(Message::CUSTOMER_TYPE, $customerId, $v['id'], 0, $content, 8);
                } catch (Exception $e) {
                    Log::write('错误信息：' . $e->getMessage());
                    Db::rollback();
                }
            }
            $obj->close_mailbox();   //Close Mail Box
        }
        echo 'over';
    }

    // 邮箱定时 api接口形式
    public function getEmailList()
    {
        $domain = 'qdsd.vip';
        $product = 'qdsd_hzqiye_ntesmail_com';
        $accounts = 'admin';
        $params = ['fids' => [1], 'order' => 'receivedDate', 'desc' => true, 'start' => 0, 'limit' => 100, 'returnTotal' => true];
        $time = date(time()) . '000';
        $res = openssl_pkey_get_private($this->prikey);
        $src = "account_name=" . $accounts . "&domain=" . $domain . "&params=" . json_encode($params) . "&product=" . $product . "&time=" . $time;
        if (openssl_sign($src, $out, $res)) {
            $sign = bin2hex($out);
            $url = "http://apihz.qiye.163.com/qiyeservice/api/mailbox/listMessages";
            $pram = $src . "&sign=" . $sign;
            echo $url . "?" . $pram . "<br>";
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $pram);

            $data = curl_exec($ch);
            curl_close($ch);
            $res = json_decode($data, true);
            dump($res);
        }
    }

    // 邮箱定时 api接口形式 开始时间到结束时间
    public function getEmails()
    {
        $domain = 'qdsd.vip';
        $product = 'qdsd_hzqiye_ntesmail_com';
        $accounts = 'admin';
        $start = date("Y-m-d", '-30day');
        $end = date("Y-m-d H:i:s");
        $page_num = "1";
        $page_size = "10";
        $time = date(time()) . '000';
        $res = openssl_pkey_get_private($this->prikey);
//        $src = "accounts=" . $accounts . "&domain=" . $domain . "&end=" . $end . "&page_num=" . $page_num . "&page_size=" . $page_size  . "&product=" . $product  . "&start=" . $start . "&time=" . $time;
        $src = "accounts=" . $accounts . "&domain=" . $domain . "&end=" . $end . "&page_num=" . $page_num . "&page_size=" . $page_size . "&product=" . $product . "&start=" . $start . "&time=" . $time;
        if (openssl_sign($src, $out, $res)) {
            $sign = bin2hex($out);
            $url = "http://apihz.qiye.163.com/qiyeservice/api/mail/getReceivedMailLogs";
            $pram = $src . "&sign=" . $sign;
            echo $url . "?" . $pram . "<br>";
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $pram);

            $data = curl_exec($ch);
            curl_close($ch);
            $res = json_decode($data, true);
            dump($res);
        }
    }

    /**
     * 打卡定时任务
     */
    public function attendance()
    {
        $w = date('w');
        $date = [
            1 => 'monday',
            2 => 'tuesday',
            3 => 'wednesday',
            4 => 'thursday',
            5 => 'friday',
            6 => 'saturday',
            0 => 'weekday',
        ];
        $weekname = $date[$w];
        $times = AttendanceTime::where([$weekname => 1])->select();
        if (empty($times)) {
            return '未设置规则';
        }
        $row = AttendanceStatisc::where(['time' => date('Y-m-d')])->find();
        if (!empty($row)) {
            return '规则已生成';
        }
        $times = collection($times)->toArray();
        $rule = AttendanceRule::where([])->find();

        $statiscs = AttendanceStatisc::where(['time' => date('Y-m-d', strtotime('-1 day'))])->select();
        foreach ($statiscs as $v) {
            $update = [];
            if (empty($t['clock_in']) && !empty($t['clock_out'])) {//缺卡
                $update['clock_in_status'] = 1;
            }
            if (empty($t['clock_out']) && !empty($t['clock_in'])) {//缺卡
                $update['clock_out_status'] = 1;
            }
            if (empty($t['clock_in']) && empty($t['clock_out'])) {//旷工
                $update['clock_in_status'] = 2;
                $update['clock_out_status'] = 2;
            }
            if ($update) {
                $statiscModel = new AttendanceStatisc();
                $statiscModel->save($update, ['id' => $v['id']]);
            }

        }
        $staff_ids = explode(',', $rule['staff_id']);

        $statisc = [];
        foreach ($staff_ids as $sid) {
            foreach ($times as $t) {
                $statisc[] = [
                    'staff_id' => $sid,
                    'number' => $t['number'],
                    'time' => date('Y-m-d'),
                    'start_time' => $t['start_time'],
                    'end_time' => $t['end_time'],
                    'ustart_time' => $t['ustart_time'],
                    'uend_time' => $t['uend_time'],
                    'dstart_time' => $t['dstart_time'],
                    'dend_time' => $t['dend_time'],
                    'start_status' => $t['start_status'],
                    'end_status' => $t['end_status'],
                ];
            }
        }
        $statiscModel = new AttendanceStatisc();
        $result = $statiscModel->allowField(true)->saveAll($statisc);
        if (empty($result)) {
            return '生成规则失败';
        }
        return '生成规则成功';
    }
    //待办跟进通知  每分钟执行
    public function daiban_notice(){
        $start_time = date('Y-m-d H:i:00');
        $end_time =  date('Y-m-d H:i:59');
        $where['status'] = 1;
        $where['next_time'] = array(array('egt',$start_time),array('elt',$end_time));
        $record = Record::where($where)->select();
        foreach($record as $k=>$v){
            $type='';
            // 1客户 2联系人 3订单 4线索 5商机
            if($v['relation_type'] == 1){
                $type = Message::CUSCORDNEXT_TYPE;
            }else if($v['relation_type'] == 3){
                $type = Message::CONTCORDNEXT_TYPE;
            }else if($v['relation_type'] == 4){
                $type = Message::LEADRECORDNEXT_TYPE;
            }else if($v['relation_type'] == 5){
                $type = Message::BUSCORDNEXT_TYPE;
            }
            if($type){
                Message::addMessage(Message::LEADS_TRANFER,$v['relation_id'],$v['staff_id'],$v['create_staff_id']);
            }
        }
        echo 'success';
    }
    //超时任务通知  每天执行一次
    public function task_over(){
        //逾期日程
        $overEventsWhere=[
            'start_time' => ['lt', date('Y-m-d', strtotime('+1 day'))],
            'end_time' => ['lt', date('Y-m-d H:i:s')],
            'status'   => ['in', [0, 1]],
        ];
        $event = Event::where($overEventsWhere)->order('id desc')->select();
        $event=collection($event)->toArray();
        foreach ($event as $k => $v) {
            Message::addMessage(Message::TASK_notice,$v['id'],$v['staff_id'],$v['create_staff_id']);
        }
    }

    public function sycn_openid()
    {
        $wechat2 = new Wechat('wxOfficialAccount');
        $batch = $wechat2->getUsers();
        if (empty($batch['data'])) {
            return '微信配置有误！';
        }

        $openid = $batch['data']['openid'];
        $model = new Staff();
        $old_openid = $model->where([])->column('openid');
        foreach ($openid as $k => $v) {
            if (in_array($v, $old_openid)) {
                unset($openid[$k]);
            }
        }
        $openid = array_values($openid);
        $openids = array_chunk($openid, 100);
        $weopen = new WechatOpenid();
        foreach ($openids as $o_ids) {
            $insertAll = [];
            $result = $wechat2->getBatchget($o_ids);
            if (empty($result['user_info_list'])) {
                return '微信配置有误！';
            }
            foreach ($result['user_info_list'] as $index => $item) {
                $unionid = $weopen->where(['unionid'=>$item['unionid']])->find();
                if(!$unionid){
                    if (isset($item['unionid'])) {
                        $model->where(['unionid'=>$item['unionid']])->update(['wx_openid'=>$item['openid']]);
                        $insertAll[] = [
                            'openid' => $item['openid'],
                            'unionid' => $item['unionid']
                        ];
                    }
                }


            }

            $weopen->insertAll($insertAll);
        }

        return 'success';
    }
}
